package cn.jimmie.learn.viewArt.captcha.internal;

import android.animation.Animator;
import android.animation.AnimatorListenerAdapter;
import android.animation.ValueAnimator;
import android.graphics.Canvas;

/**
 * function : 动画适配器,
 * 使用模板模式, 让动画设置更加简洁
 *
 * <p> Create Time: 2018年12月09日 17:25 </p>
 * <p> @author Jimmie.Qian  </p>
 */
public abstract class AnimationFuncAdapter implements AnimationFunc {
    private OnAnimationFinishListener mListener;
    private boolean mSuccess;
    private ValueAnimator mSuccessAnimator;
    private ValueAnimator mFailureAnimator;

    protected SeekCaptchaView mView;

    protected abstract ValueAnimator createSuccessAnimator();

    protected abstract ValueAnimator createFailureAnimator();

    protected abstract void drawSuccess(Canvas canvas);

    protected abstract void drawFailure(Canvas canvas);

    public AnimationFuncAdapter(SeekCaptchaView view) {
        mView = view;
    }

//    protected void updateState(int state) {
//        mView.mState = state;
//    }

    @Override
    public void init() {
        mSuccessAnimator = createSuccessAnimator();
        mFailureAnimator = createFailureAnimator();

        if (mSuccessAnimator != null)
            mSuccessAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    if (mListener != null) mListener.onFinished();
                }

                @Override
                public void onAnimationStart(Animator animation) {
                    if (mListener != null) mListener.onStarted();
                }
            });

        if (mFailureAnimator != null)
            mFailureAnimator.addListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    if (mListener != null) mListener.onFinished();
                }

                @Override
                public void onAnimationStart(Animator animation) {
                    if (mListener != null) mListener.onStarted();
                }
            });
    }

    @Override
    public void startAnimation(boolean isSuccess) {
        mSuccess = isSuccess;
        if (isSuccess && mSuccessAnimator != null) {
            mSuccessAnimator.start();
        } else if (!isSuccess && mFailureAnimator != null) {
            mFailureAnimator.start();
        }
    }

    @Override
    public void setOnAnimationFinishListener(OnAnimationFinishListener listener) {
        mListener = listener;
    }

    @Override
    public ValueAnimator getFailAnimator() {
        return mFailureAnimator;
    }

    @Override
    public void draw(Canvas canvas) {
        if (mSuccess) drawSuccess(canvas);
        else drawFailure(canvas);
    }
}
